package com.crack.nga2.localimage;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.crack.nga2.R;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LocalImageActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, Handler.Callback, SelectImageFragment.SendCallBack {
    /**
     * 存储所有的本地图片信息 String-包含图片文件夹路径 List<String>文件夹下的所有图片路径
     */
    private Map<String, List<String>> imageGroup = new HashMap<>();
    /**
     * 本地图片加载器
     */
    private NativeImageLoader nativeImageLoader;
    /**
     * 适配器
     */
    private ImageAdapter adapter = new ImageAdapter();
    private List<ImageBean> imageBeanList;
    private List<String> selectedImage = new ArrayList<>();
    /**
     * 图片大小
     */
    private Point imagePoint;
    private Map<String, SelectImageFragment> fragmentMap = new HashMap<>();
    private FragmentManager fragmentManager;
    private Handler mHandler = new Handler(this);
    private boolean fragmentIsShow = false;
    private SelectImageFragment currentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_image);
        fragmentManager = getSupportFragmentManager();
        GridView gridView = (GridView) findViewById(R.id.gridView);
        nativeImageLoader = NativeImageLoader.getInstance();
        imageBeanList = new ArrayList<>();
        imageBeanList.add(new ImageBean());
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);
        imageGroup.clear();
        getImages();
        int size = getResources().getDimensionPixelSize(R.dimen.image_size);
        int padding = getResources().getDimensionPixelOffset(R.dimen.image_padding);
        imagePoint = new Point(size - 2 * padding, size - 2 * padding);
    }


    private void getImages() {
        new Thread() {
            @Override
            public void run() {
                Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver resolver = getContentResolver();
                Cursor cursor = resolver.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " +
                                MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                if (cursor == null) {
                    return;
                }
                while (cursor.moveToNext()) {
                    //获取图片路径
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    //获取图片父目录路径
                    String parentName = new File(path).getParent();
                    if (!imageGroup.containsKey(parentName)) {
                        List<String> childList = new ArrayList<>();
                        childList.add(path);
                        imageGroup.put(parentName, childList);
                    } else {
                        imageGroup.get(parentName).add(path);
                    }
                }
                Log.i("tag",imageGroup.keySet().toString());
                mHandler.sendEmptyMessage(RESULT_OK);
                cursor.close();
            }
        }.start();
    }

    /**
     * 将imageGroup组装成ImageBean列表
     */
    private List<ImageBean> subGroupOfImage(Map<String, List<String>> group) {
        if (group.size() == 0) {
            return null;
        }
        List<ImageBean> list = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : group.entrySet()) {
            ImageBean bean = new ImageBean();
            String key = entry.getKey();
            List<String> value = entry.getValue();

            bean.setFolderName(key);
            bean.setTopImagePath(value.get(0));
            bean.setImageCounts(value.size());

            list.add(bean);
        }
        return list;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            //TODO 启动照相机
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(intent, 110);
        } else {
            ImageBean bean = (ImageBean) parent.getItemAtPosition(position);
            String folderPath = bean.getFolderName();
            List<String> images = imageGroup.get(folderPath);
            SelectImageFragment fragment = fragmentMap.get(folderPath);
            if (fragment == null) {
                fragment = new SelectImageFragment(images);
                fragmentMap.put(folderPath, fragment);
            }
            addFragment(fragment);
        }
    }

    private void addFragment(SelectImageFragment fragment) {
        fragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.fragment_pull_left, R.anim.fragment_push_right)
                .replace(R.id.container, fragment)
                .commit();
        fragmentIsShow = true;
        currentFragment = fragment;
    }

    private void removeFragment() {
        fragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.fragment_pull_left, R.anim.fragment_push_right)
                .remove(currentFragment)
                .commit();
        fragmentIsShow = false;
        currentFragment = null;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 110) {
            //TODO 照相机图片
        }
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case RESULT_OK:
                List<ImageBean> list = subGroupOfImage(imageGroup);
                if (list != null) {
                    imageBeanList.addAll(list);
                    adapter.notifyDataSetChanged();
                }
                return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        if (fragmentIsShow) {
            removeFragment();
            return;
        }
        super.onBackPressed();

    }

    @Override
    public void add(List<String> pathList) {
        selectedImage.addAll(pathList);
        removeFragment();
        Intent intent = new Intent();
        intent.putExtra("images", (ArrayList) selectedImage);
        setResult(1, intent);
    }

    public void doClick(View view) {
        switch (view.getId()){
            case R.id.action_return:
                if (fragmentIsShow) {
                    removeFragment();
                    return;
                }
                finish();
                break;
        }
    }


    private class ImageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return imageBeanList.size();
        }

        @Override
        public Object getItem(int position) {
            return imageBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, final ViewGroup parent) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(LocalImageActivity.this, R.layout.activity_local_image_item, null);
                holder.imageView = (ImageView) view.findViewById(R.id.imageView);
                holder.textView = (TextView) view.findViewById(R.id.textView);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            ImageBean bean = imageBeanList.get(position);
            String parentFolder = bean.getFolderName();
            String topPath = bean.getTopImagePath();
            int count = bean.getImageCounts();
            if (parentFolder != null) {
                String content = parentFolder + "(" + String.valueOf(count) + ")";
                holder.textView.setText(content);
            }
            if (topPath != null) {
                holder.imageView.setTag(topPath);
                Bitmap bitmap = nativeImageLoader.loadNativeImage(topPath, imagePoint, new NativeImageLoader.NativeImageCallBack() {
                    @Override
                    public void onImageLoader(Bitmap bitmap, String path) {
                        ImageView imageView = (ImageView) parent.findViewWithTag(path);
                        if (bitmap != null && imageView != null) {
                            imageView.setImageBitmap(bitmap);
                        }
                    }
                });
                if (bitmap != null) {
                    holder.imageView.setImageBitmap(bitmap);
                }
            }
            return view;
        }
    }

    private class ViewHolder {
        ImageView imageView;
        TextView textView;
    }
}
